package com.app.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.lang.reflect.Member;
import java.util.ArrayList;

import com.app.Controller.ActivityController;
import com.app.Controller.NetworkController;
import com.app.Controller.ReadWriteFileController;
import com.app.DTO.AccountDTO;
import com.app.DTO.RoleDTO;
import com.app.Network.NetworkLayer;
import com.app.Network.Protocol;
import com.app.PhanQuyen.Quyen;
import com.app.QuickAction.ActionItem;
import com.app.QuickAction.QuickAction;

import ReadWriteXML.CMember;
import android.accounts.Account;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import app.com.ModuleRole.R;

public class trucActivity extends Activity {
	public static int CODE_KICK = 101;
	public static int CODE_CHAT = 201;
	public static int CODE_STOP_TALK = 301;
	public static String IP_RESULT = "IP_RESULT";
	int port = Protocol.PORT;
	public static ArrayList<Integer> yesVote;
	public static ArrayList<Integer> noVote;

	public static Runnable showMessage;
	public static Runnable showChatMessage;
	public static Runnable dislayKickMember;

	public static Runnable showResultVoteKick;
	public static Runnable finishAct;
	public static Runnable showForm1;
	public static int timeVoteKick;
	int timeStopTalk;
	public static String message;
	public static String address;// dia chi cua nguoi ban chat rieng voi minh
	public static String chatMessage;

	public static Address ipBeingKick;
	public static Address ipBeingStopTalk;

	public static int kickVoteResult;
	public ArrayList<Quyen> quyen = null;
	public AccountDTO account = null;
	public EditText listChat;
	public EditText txtContent;
	public static Context baseContext;
	public static Handler handler = new Handler();
	public static Runnable raShowMessage;
	public static Runnable raSignout;
	public static Runnable raStopSession;
	public static Runnable raShowDanhGia;
	public static Runnable raShowBieuQuyet;
	static String loi = "";
	String ip = "";
	public static int idindex = 0;
	public static Address Address;

	private AlertDialog.Builder _builder;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dung_noi_chuyen);
		Log.d("Phu", "Vao oncreate");

		// ip = NetworkController._peer.getAddressPeer();
		listChat = (EditText) findViewById(R.id.txtListMessage);

		Button btnShow = (Button) findViewById(R.id.btnShowMess);
		btnShow.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				message = "hello";
				NetworkController.ShowMessageNotice(message);
			}
		});
		showMessage = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Show(message);
			}
		};
		showChatMessage = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				CapNhatListChat(chatMessage, address);
			}
		};
		dislayKickMember = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HienThiMHBieuQuyetKick();
			}
		};

		finishAct = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				finishActivity();
			}
		};
		// tao lao
		showForm1 = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				showFrm1();
			}
		};
		// end tao lao
		showResultVoteKick=new Runnable() {
			
			@Override
			public void run() {
				ShowResultVoteKick();
			}
		};
		Button btnStopTalking = (Button) findViewById(R.id.btnStopTalking);
		btnStopTalking.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// ShowSetTimeStopTalking();

			}
		});

		Button btnAcceptTalking = (Button) findViewById(R.id.btnContinouTalking);
		btnAcceptTalking.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				NetworkController.GuiChoPhepNoiChuyen(new Address("TRUC@192.168.1.77:" + port));
				Log.d("Phu", "vao onclick cho noi");
			}
		});

		txtContent = (EditText) findViewById(R.id.txtMessage);

		Button btnSendMessage = (Button) findViewById(R.id.btnSendMessage);
		btnSendMessage.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				NetworkController.GuiTinNhanChat(new Address("TRUC@192.168.1.77:" + port), txtContent.getText()
						.toString());
				Log.d("Phu", "vao onclick gui tin");
				txtContent.setText("");
			}
		});

		Button btnKick = (Button) findViewById(R.id.btnKickMember);
		btnKick.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// ShowSetTimeVoteKick();
			}
		});

		Button btnThongKe = (Button) findViewById(R.id.btnThongKe);
		btnThongKe.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				NetworkController.DislayResultVoteKick();
			}
		});

		// tao lao

		Button btnTest = (Button) findViewById(R.id.btnTest);
		btnTest.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				NetworkController.ShowForm1();
			}
		});

		// -----------------An

		// Khai bao & bat su kien Onclick Button Sign Out khoi Nhom
		Button btn_SignOut = (Button) findViewById(R.id.btnSignOut);
		btn_SignOut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				NetworkController.sendGroupSignOut("MES@192.168.1.77:" + port);

				trucActivity.this.finish();
			}
		});

		// Runable raShowMessage loi
		raShowMessage = new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				showMessage(loi);
			}
		};

		// Runable raSignOut
		raSignout = new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d("Phu", "vao 'raSignout'");
				showMessageSignOut();
			}
		};

		// Khai bao & bat su kien Onclick Button Danh gia
		// "Ban than & nguoi khac"
		Button btnDanhGia = (Button) findViewById(R.id.btnDanhGia);
		btnDanhGia.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				NetworkController.sendGroupDanhGia("192.168.1.88:" + port);
				NetworkController.sendGroupDanhGia("192.168.1.99:" + port);
			}
		});

		// Runalbe raShowDanhGia
		raShowDanhGia = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// Hien thong bao yeu cau nguoi khac Danh gia
				displayNotificationDanhGia();
			}
		};

		// Khai bao & bat su kien Onclick Button Xem Danh Gia
		Button btnviewdanhgia = (Button) findViewById(R.id.btnViewDanhGia);
		btnviewdanhgia.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(trucActivity.this, frmResultDanhGiaActivity.class);
				startActivity(i);
			}
		});

		// Cac khai bao QuickAction

		// vote100accept action item
		ActionItem vote100accept = new ActionItem();

		vote100accept.setTitle("100% Accept");
		vote100accept.setIcon(getResources().getDrawable(R.drawable.ic_add));

		// vote75accept action item
		ActionItem vote75accept = new ActionItem();

		vote75accept.setTitle("75% Accept");
		vote75accept.setIcon(getResources().getDrawable(R.drawable.ic_accept));

		// vote50accept action item
		ActionItem vote50accept = new ActionItem();

		vote50accept.setTitle("50% Accept");
		vote50accept.setIcon(getResources().getDrawable(R.drawable.ic_up));

		final QuickAction mQuickAction = new QuickAction(this);
		// add QuickAction
		mQuickAction.addActionItem(vote100accept);
		mQuickAction.addActionItem(vote75accept);
		mQuickAction.addActionItem(vote50accept);

		// setup the action item click listener
		mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(int pos) {

				if (pos == 0) { // Add item selected
					// Toast.makeText(frmGroupActivity.this,
					// "Add item selected", Toast.LENGTH_SHORT).show();
					NetworkController.sendGroupBieuQuyet("192.168.1.88:" + port, 1, 60);
				} else if (pos == 1) { // Accept item selected
					// Toast.makeText(frmGroupActivity.this,
					// "Accept item selected", Toast.LENGTH_SHORT).show();
					NetworkController.sendGroupBieuQuyet("192.168.1.88:" + port, 2, 60);
				} else if (pos == 2) { // Upload item selected
					// Toast.makeText(frmGroupActivity.this,
					// "Upload items selected", Toast.LENGTH_SHORT).show();
					NetworkController.sendGroupBieuQuyet("192.168.1.88:" + port, 3, 60);
				}
			}
		});

		// Khai bao & bat su kien OnClick Button Bieu Quyet - show ra
		// QuickAction
		Button btnbieuquyet = (Button) findViewById(R.id.btnBieuQuyet);
		btnbieuquyet.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// NetworkController.sendGroupBieuQuyet("192.168.1.6:" + port);
				mQuickAction.show(v);
				mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
			}
		});

		// Runable raShowBieuQuyet
		raShowBieuQuyet = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// hien thong bao yeu cau Bieu Quyet
				displayNotificationBieuQuyet();
			}
		};

		// Khai bao & bat su kien Onclick Button Xem Bieu Quyet
		Button btnviewbieuquyet = (Button) findViewById(R.id.btnViewBieuQuyet);
		btnviewbieuquyet.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(trucActivity.this, frmResultBieuQuyetActivity.class);
				startActivity(i);
			}
		});
	}

	// **************************************
	//
	// -----Ham con - SUB FUNCTION----
	//
	// **************************************

	public void ShowSetTimeVoteKick(final String IP) {
		final EditText txtTime = new EditText(this);
		txtTime.setSingleLine();
		txtTime.setInputType(2);
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Chọn thời gian biểu quyết")
				.setMessage("Thời gian được tính bằng giây.").setView(txtTime)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String StrTime = txtTime.getText().toString();
						int time = Integer.parseInt(StrTime);
						timeVoteKick = time;
						yesVote = new ArrayList<Integer>();
						noVote = new ArrayList<Integer>();
						ipBeingKick = new Address(IP);
						ArrayList<CMember> memberList = ReadWriteFileController
								.readMember(ReadWriteFileController.MEMBER_PATH);
						for (CMember member : memberList) {
							NetworkController.SendVoteKickMember(new Address(member.get_ip()), ipBeingKick, time);
						}
						Log.d("Phu", "Da gui xong kick");
						// dem thoi gian
						long kickTime = timeVoteKick * 1000;

						CountDownTimer timer = new CountDownTimer(kickTime, 1000) {
							@Override
							public void onTick(long millisUntilFinished) {

							}

							@Override
							public void onFinish() {
								 Toast.makeText(getBaseContext(), "xong phim"+yesVote.size(),
								 Toast.LENGTH_SHORT).show();
								NetworkController.DislayResultVoteKick();
							}
						}.start();
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).create();
		dlg.show();

	}

	public void ShowSetTimeStopTalking() {
		final EditText txtTimeTalk = new EditText(this);
		txtTimeTalk.setSingleLine();
		txtTimeTalk.setInputType(2);
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Chọn thời gian buộc ngừng thảo luận")
				.setMessage("Thời gian được tính bằng giây.").setView(txtTimeTalk)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String StrTime = txtTimeTalk.getText().toString();
						int time = Integer.parseInt(StrTime);
						timeStopTalk = time;
						ipBeingStopTalk = new Address("TRUC@192.168.1.77:" + port);
						NetworkController.GuiYeuCauNgungNoi(ipBeingStopTalk, time);
						Log.d("Phu", "vao onclick ngung noi");
						long timeLong = timeStopTalk * 1000;
						Toast.makeText(getBaseContext(), timeLong + "", 1).show();
						CountDownTimer timer = new CountDownTimer(timeLong, 1000) {

							@Override
							public void onTick(long millisUntilFinished) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onFinish() {
								// TODO Auto-generated method stub
								Toast.makeText(getBaseContext(), "Het gio", 1).show();
								NetworkController.GuiChoPhepNoiChuyen(ipBeingStopTalk);
							}
						}.start();
					}

				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).create();
		dlg.show();

	}

	@Override
	public void onStart() {
		super.onStart();
		Log.d("Phu", "vao onstart");
		if (NetworkController._peer == null) {

			Log.d("Phu", "vao if activity");
			account = new AccountDTO();
			NetworkController.init("MES", port, account);
			NetworkController.resetRole();
			Log.d("Phu", NetworkController._peer.getAddressPeer());
			this.setTitle(NetworkController._peer.getAddressPeer());
			baseContext = getBaseContext();
		}
	}

	public void Show(String message) {
		// Toast.makeText(this, "hehe Xin chao", Toast.LENGTH_SHORT).show();
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo").setMessage(message)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				}).create();
		dlg.show();
	}

	public void ShowResultVoteKick() {
		Log.d("Phu","ShowResultVoteKick");
		if (yesVote.size() > 0 || noVote.size() > 0) {
			Log.d("Phu","ShowResultVoteKick YES");
			String message = "Kết quả biểu quyết : ";
			// message+="\n yes : "+yesVote.size();
			// message+=" no : "+noVote.size()+"\n";
			int sizeALL = yesVote.size() + noVote.size();
			float yesPer = (float) yesVote.size() / sizeALL * 100;
			float noPer = (float) noVote.size() / sizeALL * 100;
			int yesPercent, noPercent;
			yesPercent = (int) yesPer;
			noPercent = (int) noPer;
			// message+="\n All: "+sizeALL+
			// ", yesPer="+yesPercent+", noPer="+noPercent;
			message += yesPercent + "% đồng ý và " + noPercent + "% không đồng ý.\n";
			if (yesPercent >= noPercent) {
				kickVoteResult = 1;// bi moi ra khoi nhom
				message += "Kết quả cuối cùng là: YES";
			} else {
				kickVoteResult = 0;// khong bi moi ra khoi nhom
				message += "Kết quả cuối cùng là: NO";
			}
			message += "\n Gửi kết quả tới các thành viên trong nhóm?";
			AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo kết quả biểu quyết")
					.setMessage(message).setPositiveButton("OK", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {						
							ArrayList<CMember> memberList=ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
							for(CMember member:memberList){
								Log.d("Phu","gui toi "+member.get_ip());
								NetworkController.SendResultVoteKickMember(new Address(member.get_ip()),
										kickVoteResult, ipBeingKick);
							}
						}
					}).setNegativeButton("NO", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

						}
					}).create();
			dlg.show();
		} else {
			//NetworkController._peer.getAccount().getRuleById(id)
			Log.d("Phu","ShowResultVoteKick NO");
			NetworkController.ShowMessageNotice("Không có ai tham gia biểu quyết.");
			NetworkController.SendResultVoteKickMember(new Address(ipBeingKick), kickVoteResult, ipBeingKick);
		}
	}

	public void CapNhatListChat(String mess, String add) {
		String s = listChat.getText().toString();
		s += "\n" + add + " :" + mess;
		// s+=NetworkController._peer.getAccount().getRule().get(0).getSend();
		listChat.setText(s);

	}

	public void HienThiMHBieuQuyetKick() {
		Log.d("Phu","vao ham HienThiMHBieuQuyetKick");
		Intent i = new Intent(this.getBaseContext(), frmBieuQuyetMoiRoiNhom.class);
		startActivity(i);
	}

	// tao lao
	public void showFrm1() {
		Intent i = new Intent(getBaseContext(), HelloForm1.class);
		startActivity(i);
	}

	// hàm thống kê kết quả phản hồi
	public int ThongKeKetQuaBieuQuyetKick() {
		int kq = -1;
		int sizeALL = yesVote.size() + noVote.size();
		int yesPercent = yesVote.size() / sizeALL * 100;
		int noPercent = noVote.size() / sizeALL * 100;
		if (yesPercent >= noPercent) {
			kq = 1;// bi moi ra khoi nhom

		} else {
			kq = 0;// khong bi moi ra khoi nhom

		}
		return kq;
	}

	public void finishActivity() {
		finish();
	}

	// -----------An
	public static void show(String message) {
		loi = message;
		handler.post(raShowMessage);

	}

	public void showMessage(String message) {
		Log.d("PEERDROID", "toi show message");
		AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.setMessage(message);
		alert.setTitle("test");
		alert.show();
	}

	public void showMessageSignOut() {
		Log.d("PEERDROID", "vao day");
		Toast.makeText(this, NetworkController._peer.getAddressPeer() + " da roi nhom", Toast.LENGTH_SHORT).show();
	}

	public void displayNotificationDanhGia() {
		Intent intent = new Intent(trucActivity.this, frmDanhGiaActivity.class);
		intent.putExtra("ID", 2);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.ic_launcher, "Co yeu cau Danh gia", System.currentTimeMillis());
		notif.setLatestEventInfo(this, "Danh gia ", "Vao de", pendingIntent);

		notiManager.notify(2, notif);
		Log.d("PEERDROID", "het show notifi danh gia");
	}

	public void displayNotificationBieuQuyet() {
		Intent intent = new Intent(this, frmBieuQuyetActivity.class);
		Bundle ex = new Bundle();
		ex.putInt("ID", 3);
		ex.putInt("INDEX", idindex);
		ex.putString("SENDER", String.valueOf(Address));
		intent.putExtras(ex);
		// intent.putExtra("ID", 3);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.ic_launcher, "Co yeu cau Bieu Quyet",
				System.currentTimeMillis());
		notif.setLatestEventInfo(this, "Bieu quyet ", "Vao de", pendingIntent);

		notiManager.notify(3, notif);
		Log.d("PEERDROID", "het show notifi bieu quyet");
	}

	public static void showNotificationBieuQuyet(int index, Address sender) {
		Log.d("PEERDROID", " da vao shownotifi......");
		idindex = index;
		Address = sender;

		Log.d("PEERDROID", "vao frm truc" + String.valueOf(index) + String.valueOf(sender));
		handler.post(raShowBieuQuyet);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(getApplication()).inflate(R.menu.omnu_thao_luan, menu);
		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.mnuDanhSachThanhVien:
			Intent iDanhSachThanhVien = new Intent(getBaseContext(), frmDanhSachThanhVienActivity.class);
			startActivityForResult(iDanhSachThanhVien, CODE_KICK);
			break;
		case R.id.mnuChiaSeTaiLieu:
			Toast.makeText(getBaseContext(), "Chia sẻ tài liệu", 1).show();
			break;
		default:
			break;
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CODE_KICK) {
			if (resultCode == RESULT_OK) {
				String ip = data.getStringExtra(IP_RESULT);
				if (ip != null) {
					ShowSetTimeVoteKick(ip);
				}
			}
		}
	}
}
